package com.elitetyc.eliteim.server.handler.impl;

import com.elitetyc.eliteim.common.handler.HeartBeatHandler;
import com.elitetyc.eliteim.server.config.IMServerProperties;
import com.elitetyc.eliteim.server.holder.SessionSocketHolder;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author yuanchao.tan
 * @version 1.0
 * @description 服务端心跳处理器
 * @Date 2021/9/16 15:53
 */
@Component
public class IMServerHeartBeatHandler implements HeartBeatHandler {
    public static final AttributeKey<Long> ATTRIBUTE_KEY_READ_TIME = AttributeKey.valueOf("readTime");
    @Autowired
    private IMServerProperties imServerProperties;

    @Override
    public void process(ChannelHandlerContext ctx) {
        final Channel channel = ctx.channel();
        if (channel.hasAttr(ATTRIBUTE_KEY_READ_TIME)) {
            final Long lastReadTime = channel.attr(ATTRIBUTE_KEY_READ_TIME).get();
            final long currentTimeMillis = System.currentTimeMillis();
            if (currentTimeMillis - lastReadTime > imServerProperties.getHeartBeatTime() * 1000) {
                // 如果超过了规定的心跳检测时间都没有收到客户端的心跳包，移除连接信息
                SessionSocketHolder.removeSession((NioSocketChannel) channel);
                // 关闭通道
                channel.close();
            }
        }
    }
}
